package com.congee02.sync;

import com.congee02.ThreadProvider;

/**
 * @author congee02
 * @date 2/2/2023 3:36 PM
 */
public class SynchronizedObjectSellTicketTest {

    private final static int NUM_OF_WINDOWS = 3;

    private static Thread[] generateWindows() {
        ThreadProvider provider = new SynchronizedObjectSellTicketThread();
        Thread[] windows = new Thread[NUM_OF_WINDOWS];
        for (int i = 0 ; i < windows.length ; i ++ ) {
            windows[i] = provider.thread("windows" + i);
        }
        return windows;
    }

    public static void main(String[] args) {
        Thread[] windows = generateWindows();
        for (Thread w : windows) {
            w.start();
        }
    }
    
    private static class SynchronizedObjectSellTicketThread implements ThreadProvider {

        private Integer ticketNum = 100;

        private Object objectLock = new Object();

        /**
         * 尝试售票，成功返回 true，失败返回 false
         */
        public boolean trySell() {
            
            synchronized (objectLock) {
                if (ticketNum <= 0) {
                    return false;
                }

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + " 售出一张票，剩余票数: " + --ticketNum);

                return true;
            }
        
        }

        @Override
        public void run() {
            System.out.println(objectLock);
            while (ticketNum > 0) {
                if (! trySell()) {
                    break;
                }
            }
            System.out.println(Thread.currentThread().getName() + " 售票结束");
        }
    }
}
